#include "aliyun.h"

/*本地变量*/
WiFiClient espclient;
static bool connect_to_aliyun_flag = false;

/*全局变量*/
PubSubClient client(espclient);

void Connect_To_Aliyun(void)
{
    client.setServer(aliyun_server,aliyun_port);
    while(!client.connect(mqtt_client_id,mqtt_username,mqtt_password))
    {

    }

    connect_to_aliyun_flag = true;

    Serial.println("Connect To aliyun success");
    Serial.printf("Connect To Aliyun:%d\r\n",esp_get_free_heap_size());
    // client.connect(mqtt_client_id,mqtt_username,mqtt_password);
    // if(client.connected())
    // {
    //     Serial.println("client connects Aliyun success first");
    //     Serial.printf("ESP32 HEAP:%d\r\n",esp_get_free_heap_size());
    // }
    // else
    // {
        
    // }
}

void Aliyun_Loop(void)
{
    // if(client.connected())
    // {
    //     client.loop();
    // }
    if(connect_to_aliyun_flag == true)
    {
        client.loop();
    }
    //Serial.printf("ESP32 HEAP:%d\r\n",esp_get_free_heap_size());
}

void Disconnect_To_Aliyun(void)
{
    if(connect_to_aliyun_flag == true)
    {
        client.disconnect();
        Serial.println("Disconnect To Aliyun success");
        Serial.printf("Disconnect_To_Aliyun:ESP32 HEAP:%d\r\n",esp_get_free_heap_size());
        connect_to_aliyun_flag = false;
    }
}